<template>
  <div class="student-homework-management">
    <!-- 搜索区域 -->
    <el-card class="filter-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="作业ID">
            <el-input
              v-model="filterForm.assignmentId"
              placeholder="请输入作业ID"
              @keyup.enter="queryHomeworkDetail"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <el-button type="primary" @click="queryHomeworkDetail">查询</el-button>
            <el-button type="default" @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-card>

    <el-dialog
      v-model="queryDialogVisible"
      title="作业信息查询结果"
      width="50%"
      @close="handleQueryDialogClose"
    >
      <el-form :model="queryHomeworkInfo" label-width="120px">
        <el-form-item label="作业ID">
          <el-input v-model="queryHomeworkInfo.assignmentId" disabled></el-input>
        </el-form-item>
        <el-form-item label="作业标题">
          <el-input v-model="queryHomeworkInfo.title" disabled></el-input>
        </el-form-item>
        <el-form-item label="作业内容">
          <el-input v-model="queryHomeworkInfo.content" disabled></el-input>
        </el-form-item>
        <el-form-item label="开始时间">
          <el-input v-model="queryHomeworkInfo.startTime" disabled></el-input>
        </el-form-item>
        <el-form-item label="截止时间">
          <el-input v-model="queryHomeworkInfo.dueTime" disabled></el-input>
        </el-form-item>
        <el-form-item label="作业状态">
          <el-input v-model="queryHomeworkStatusText" disabled></el-input>
        </el-form-item>
        <el-form-item label="作业附件">
          <el-button
            v-if="queryHomeworkInfo.attachment"
            type="text"
            @click="downloadAttachment(queryHomeworkInfo.attachment)"
          >下载附件</el-button>
          <span v-else>无附件</span>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 作业列表 -->
    <el-card class="homework-list-card">
      <div class="table-container">
        <el-table
          :data="homeworkList"
          stripe
          border
          @row-dblclick="handleRowClick"
          style="width: 100%;"
          max-height="500px"
        >
          <el-table-column prop="assignmentId" label="作业ID"></el-table-column>
          <el-table-column prop="title" label="作业标题"></el-table-column>
          <el-table-column prop="content" label="作业内容"></el-table-column>
          <el-table-column prop="attachment" label="作业附件">
            <template #default="scope">
              <el-button
                v-if="scope.row.attachment"
                type="text"
                @click="downloadAttachment(scope.row.attachment)"
              >下载附件</el-button>
              <span v-else>无附件</span>
            </template>
          </el-table-column>
          <el-table-column prop="startTime" label="开始时间"></el-table-column>
          <el-table-column prop="dueTime" label="截止时间"></el-table-column>
          <el-table-column prop="stateSubmission" label="作业状态">
            <template #default="scope">{{ getStatusText(scope.row.stateSubmission) }}</template>
          </el-table-column>
          <el-table-column prop="grade" label="成绩"></el-table-column>
          <el-table-column prop="feedback" label="评语"></el-table-column>
          <el-table-column prop="subDate" label="提交时间"></el-table-column>

          <el-table-column prop="attachmentSubmission" label="提交的附件">
            <template #default="scope">
              <el-button
                v-if="scope.row.attachmentSubmission"
                type="text"
                @click="downloadAttachment(scope.row.attachmentSubmission)"
              >下载附件</el-button>
              <span v-else>无附件</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button
                v-if="getStatusText(scope.row.stateSubmission) != '已批改'"
                type="primary"
                size="small"
                @click="handleSubmit(scope.row)"
              >提交作业</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页组件 -->
      <el-pagination
        class="pagination"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        :current-page="currentPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 提交作业对话框 -->
    <el-dialog
      v-model="submitDialogVisible"
      title="提交作业"
      width="50%"
      @close="handleSubmitDialogClose"
    >
      <el-form :model="submitForm" ref="submitFormRef" label-width="120px" :rules="submitFormRules">
        <el-form-item label="作业ID" prop="assignmentId">
          <el-input v-model="submitForm.assignmentId" disabled></el-input>
        </el-form-item>
        <el-form-item label="作业标题" prop="title">
          <el-input v-model="submitForm.title" disabled></el-input>
        </el-form-item>
        <el-form-item label="作业附件" prop="file">
          <input
            type="file"
            ref="attachmentInput"
            style="display: none;"
            @change="handleAttachmentChange"
          />
          <el-button @click="openAttachmentSelector">选择文件</el-button>
          <span v-if="submitForm.attachmentName">{{ submitForm.attachmentName }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="submitDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAssignment">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRoute } from "vue-router";

const route = useRoute();

// 筛选条件
const filterForm = reactive({
  assignmentId: "",
  // title: "",
  // content: "",
  // startTime: "",
  // dueTime: "",
  // stateSubmission: "",
  // courseId:"",
  teachId:Number(route.query.teachId) || "",// 接收传递过来的课程 teachId，如果没有则为空
  classIds:localStorage.getItem("classId"),
  // grade: "",
  // feedback: "",
  // subDate: "",
  studentId: "",
  // attachment: "",
  // attachmentSubmission: ""
});

// 表格数据和分页
const homeworkList = ref([]);
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);

// 查询对话框相关
const queryDialogVisible = ref(false);
const queryHomeworkInfo = ref({
  assignmentId: "",
  title: "",
  content: "",
  startTime: "",
  dueTime: "",
  stateSubmission: "",
  attachment: null
});

// 提交作业相关
const submitDialogVisible = ref(false);
const submitForm = ref({
  assignmentId: "",
  title: "",
  file: null,
  attachmentName: null
});
const submitFormRef = ref(null);
const attachmentInput = ref(null);

// 查询作业详情
const queryHomeworkDetail = async () => {
  const assignmentId = filterForm.assignmentId;
  if (!assignmentId) {
    ElMessage.warning("请输入作业ID");
    return;
  }
  try {
    const response = await axios.get(
      `/assignments/getAssignmentDetail?assignmentId=${assignmentId}`
    );
    if (response.data.flag) {
      queryHomeworkInfo.value = response.data.result;
      queryDialogVisible.value = true;
    } else {
      ElMessage.error(response.data.reason || "查询失败");
    }
  } catch (error) {
    console.error("查询出错:", error);
    ElMessage.error("查询时发生错误，请稍后重试");
  }
};

// 重置筛选条件
const resetFilter = () => {
  filterForm.assignmentId = "";
  // filterForm.title = "";
  // filterForm.content = "";
  // filterForm.startTime = "";
  // filterForm.dueTime = "";
  // filterForm.stateSubmission = "";
  // filterForm.classIds = "";
  // filterForm.grade = "";
  // filterForm.feedback = "";
  // filterForm.subDate = "";
  // filterForm.teachId = "";
  fetchHomeworks();
};

// 获取作业列表
const fetchHomeworks = async () => {
  try {
    const params = {
      ...filterForm,
      page: currentPage.value,
      size: pageSize.value,
      studentId:localStorage.getItem("studentId")
    };
    const formData = new FormData();
    formData.append("classIds",filterForm.classIds);
    formData.append("assignmentId",filterForm.assignmentId);
    formData.append("teachId",filterForm.teachId);
    formData.append("page",currentPage.value);
    formData.append("size",pageSize.value);
    formData.append("studentId",localStorage.getItem("studentId"));
    const response = await axios.post('/assignments/selectAssignmentAndSubmissionByInfos',formData);
    if (response.data.flag) {
      homeworkList.value = response.data.result || [];
      console.log(homeworkList.value);//获取学生作业列表
      total.value = response.data.total || 0;
    } else {
      ElMessage.error(response?.data.message || "获取作业列表失败");
    }
  } catch (error) {
    console.error("获取作业列表失败", error);
    ElMessage.error("获取作业列表失败，请稍后重试");
  }
};

// 分页控制
const handleSizeChange = newSize => {
  pageSize.value = newSize;
  fetchHomeworks();
};

const handleCurrentChange = newPage => {
  currentPage.value = newPage;
  fetchHomeworks();
};

// 处理提交作业
const handleSubmit = row => {
  submitDialogVisible.value = true;
  submitForm.value = {
    assignmentId: row.assignmentId,
    title: row.title,
    file: null,
    attachmentName: null
  };
};

// 提交作业
const submitAssignment = async () => {
  await submitFormRef.value.validate(async valid => {
    if (!valid) {
      return;
    }
    try {
      const formData = new FormData();
      const { assignmentId, file } = submitForm.value;
      const studentId = localStorage.getItem("studentId");

      formData.append("assignmentId", assignmentId);
      formData.append("studentId", studentId);
      if (file) {
        formData.append("file", file);
      }

      const response = await axios.post(
        "/submissions/addAndUpdateSubmissionStd",
        formData,
        {
          headers: {
            "Content-Type": "multipart/form-data"
          }
        }
      );

      if (response.data.flag) {
        // console.log(response.data.result);
        ElMessage.success("作业提交成功！");
        submitDialogVisible.value = false;
        submitFormRef.value.resetFields();
        submitForm.value.attachmentName = null;
        fetchHomeworks();
      } else {
        ElMessage.error("提交失败！");
      }
    } catch (error) {
      console.log(error);
    }
  });
};

// 提交表单验证规则
const submitFormRules = computed(() => ({
  file: [
    {
      required: true,
      message: "请上传新作业附件（DOCX文件）",
      trigger: "change"
    }
  ]
}));

// 处理查询对话框关闭
const handleQueryDialogClose = () => {
  queryDialogVisible.value = false;
  queryHomeworkInfo.value = {
    assignmentId: "",
    title: "",
    content: "",
    startTime: "",
    dueTime: "",
    stateSubmission: "",
    attachment: null
  };
};

// 处理提交对话框关闭
const handleSubmitDialogClose = () => {
  submitDialogVisible.value = false;
  submitForm.value = {
    assignmentId: "",
    title: "",
    file: null,
    attachmentName: null
  };
};

// 处理附件选择
const handleAttachmentChange = e => {
  submitForm.value.file = e.target.files[0];
  submitForm.value.attachmentName = e.target.files[0].name;
};

// 打开附件选择器
const openAttachmentSelector = () => {
  const input = attachmentInput.value;
  input.click();
};

// 根据状态码返回中文描述
const getStatusText = stateSubmission => {
  switch (stateSubmission) {
    case null:
      return "未提交";
    case "2":
      return "未批改";
    case "3":
      return "已批改";
    default:
      return "未知";
  }
};

// 计算属性，用于查询结果对话框中显示状态中文描述
const queryHomeworkStatusText = computed(() => {
  return getStatusText(queryHomeworkInfo.value.state);
});

// 下载附件
const downloadAttachment = async attachment => {
  console.log(attachment);
  try {
    const response = await axios.put(
      `/attachments/downloadAttachmentByAttachmentId?attachmentId=${attachment}`
    );

    if (response.data.flag) {
      let fileName = 'document.docx';
      const contentDisposition = response.headers['content-disposition'];
      if (contentDisposition) {
        const fileNameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
        if (fileNameMatch && fileNameMatch[1]) {
          fileName = fileNameMatch[1].replace(/['"]/g, '');
        }

    }
    // 创建下载链接
      const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', fileName);
      document.body.appendChild(link);

      // 执行下载
      link.click();

      // 清理资源
      setTimeout(() => {
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
      }, 100);
    } else {
      ElMessage.error('下载失败，服务器返回错误');
    }
  } catch (error) {
    console.error("下载附件出错:", error);
    ElMessage.error("下载附件时发生错误，请稍后重试");
  }
};

onMounted(() => {
  fetchHomeworks();
});
</script>

<style scoped>
.student-homework-management {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.homework-list-card {
  height: auto;
  margin-bottom: 20px;
}

.table-container {
  height: 500px;
  overflow-y: auto;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>